package com.jamin.msg.ui;

import com.jamin.msg.R;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Audio;
import android.telephony.SmsMessage;
import android.util.Log;

public class MessageBroadcastReceiver extends BroadcastReceiver{

	private static boolean DEBUG = true;
	private static final String TAG = "MessageBroadcastReceiver=====wangjieming";
	SharedPreferences sp ;
	NotificationManager notification;
	Context ctx;
	String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		
		// TODO Auto-generated method stub
		if(DEBUG)Log.d(TAG, "receive sms notification");
		ctx = context;
		notification = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		sp = PreferenceManager.getDefaultSharedPreferences(ctx);
		if(sp.getBoolean(MessagePreferenceActivity.PREF_KEY_MSG_NOTICE_SETTING, false)){
			

			if (SMS_RECEIVED_ACTION.equals(intent.getAction())){

				Bundle bundle = intent.getExtras();			 
				if (bundle != null){			 
					Object[] pdus = (Object[])bundle.get("pdus");
					for (Object pdu : pdus){
						SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
						String sender = message.getOriginatingAddress();
						setNotiType(R.drawable.receive_message, sender);
					}
				}
			}
		}
	}


	private void setNotiType(int id,String msg) {
		// TODO Auto-generated method stub
		Intent notifyIntent = new Intent();
		//	notifyIntent.setAction(Intent.ACTION_SEND);

		notifyIntent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");

		PendingIntent appIntent = PendingIntent.getActivity(ctx, 0, notifyIntent, 0);

		Notification noti = new Notification();
		noti.icon = id;
		noti.tickerText = msg;
		noti.defaults = Notification.DEFAULT_SOUND;
		noti.flags = Notification.FLAG_AUTO_CANCEL;
		noti.setLatestEventInfo(ctx, msg, "短信息", appIntent);
		

		/**
		 * 设置震动
		 * 第一个参数为开始之前的震动时间
		 * 第二个参数为首次震动的长度
		 * 第三个参数为暂停的时间
		 * 第四个参数为震动时间
		 * noti.defaults |= Notification.DEFAULT_VIBRATE;//设置默认震动 
		 * 
		 */	
		long[] vibrate = {0,100,200,300}; 		
		noti.vibrate = vibrate ;
		/**
		 * 设置提示音
		 * noti.defaults |= Notification.DEFAULT_SOUND; //设置默认铃声
		 * noti.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,"6");//通过ContentProvider在MediaStore中查到的
		 */		
	//	noti.sound = Uri.parse("file:/sdcard/notification/ringer.mp3"); 
		
		
		/**
		 * 发出通知
		 */
		notification.notify(0, noti);

	}


}
